package day07;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author zouran
 * createDate：2024/7/3  19:57
 */
public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(10000);
        while (true) {
            Socket socket = server.accept();
            new Thread(() -> {
                try {
                    InputStream in = socket.getInputStream();
                    OutputStream out = socket.getOutputStream();
                    while (true) {
                        if (handleMessage(in))
                            break;
                        if (sendMessage(out))
                            break;
                    }
                    in.close();
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }

    public static boolean handleMessage(InputStream in) {
        String message;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            message = reader.readLine();
            System.out.println("收到信息:" + message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Objects.equals("bye", message);
    }

    public static boolean sendMessage(OutputStream out) {
        String message;
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入发送信息:");
            message = scanner.nextLine();
            writer.write(message + '\n');
            writer.flush();
            System.out.println("发送成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Objects.equals("bye", message);
    }
}
